package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.common.exception.ExceptionCatch.CustException;
import com.heima.model.behavior.dtos.*;
import com.heima.model.behavior.pojos.*;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ApBehaviorEntryService behaviorEntryService;


    @Override
    public synchronized ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        //1. 判断userId是否为空  不为空 使用userId查询  如果不存在基于userId创建实体数据
        if (userId != null) {
            // 根据 type类型为用户关联  和  refId查询 是否有对应关联行为实体
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(Query.query(Criteria.where("refId").is(userId)
                    .and("type").is(ApBehaviorEntry.Type.USER.getCode())), ApBehaviorEntry.class);

            // 如果行为实体为 null
            if (behaviorEntry == null) {

                // 创建对应行为实体
                behaviorEntry = new ApBehaviorEntry();
                behaviorEntry.setType(ApBehaviorEntry.Type.USER.getCode());
                behaviorEntry.setRefId(userId);
                behaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(behaviorEntry);
            }
            return behaviorEntry;
        }
        //2. 判断设备id是否为空   不为空 使用设备id查询  如果不存在基于设备id创建实体数据
        if (equipmentId != null) {
            // 根据 type类型为设备关联  和  refId查询 是否有对应关联行为实体
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(Query.query(Criteria.where("refId").is(equipmentId)
                    .and("type").is(ApBehaviorEntry.Type.EQUIPMENT.getCode())), ApBehaviorEntry.class);
            if (behaviorEntry == null) {
                behaviorEntry = new ApBehaviorEntry();
                behaviorEntry.setType(ApBehaviorEntry.Type.EQUIPMENT.getCode());
                behaviorEntry.setRefId(equipmentId);
                behaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(behaviorEntry);
            }
            return behaviorEntry;
        }
        return null;
    }

    @Override
    public ResponseResult like(LikesBehaviorDTO dto) {// 1. 校验参数

        // 2. 根据当前登录用户id查询行为实体对象
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        // 3. 如果是点赞操作  判断是否已经点过赞
        Integer id = user.getId();
        ApBehaviorEntry behaviorEntry = findByUserIdOrEquipmentId(id, dto.getEquipmentId());
        Query query = Query.query(Criteria
                .where("entryId").is(behaviorEntry.getId())
                .and("articleId").in(dto.getArticleId())
        );
        ApLikesBehavior one = mongoTemplate.findOne(query, ApLikesBehavior.class);
        Short operation = dto.getOperation();
        if (one == null) {//没有点赞  只能0  不能1
            //判断是点赞还是取消点赞
            if (operation == 0) {
                // 4. 没有点过赞则 像mongo点赞集合中 添加点赞数据
                ApLikesBehavior behavior = new ApLikesBehavior();
                behavior.setArticleId(dto.getArticleId());
                behavior.setCreatedTime(new Date());
                behavior.setEntryId(behaviorEntry.getId());
                mongoTemplate.save(behavior);
            } else {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
        } else {//点过赞了已经  不能在点  0就抛异常  1就取消
            if (operation == 0) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST);
            } else {
                // 5. 如果是取消点赞操作  在mongo点赞集合中 删除对应点赞数据
                mongoTemplate.remove(query, ApLikesBehavior.class);
            }
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        //1. 校验参数 文章id必须传
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            user = new ApUser();
        }
        //2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        ApBehaviorEntry behaviorEntry = findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        //3. 判断阅读行为是否存在
        ApReadBehavior readBehavior = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(behaviorEntry.getId())
                .and("articleId").is(dto.getArticleId())), ApReadBehavior.class);
        //4. 存在  将阅读行为的count字段加1 并修改
        if (readBehavior != null) {
            readBehavior.setCount((short) (readBehavior.getCount() + 1));
            readBehavior.setUpdatedTime(new Date());
            mongoTemplate.save(readBehavior);
        } else {
            //5. 不存在  创建阅读行为 并初始化count字段值为 1
            readBehavior = new ApReadBehavior();
            readBehavior.setEntryId(behaviorEntry.getId());
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setCount((short) 1);
            readBehavior.setCreatedTime(new Date());
            mongoTemplate.insert(readBehavior);
        }
        return ResponseResult.okResult();
    }

    //
    @Override
    public ResponseResult unlikeBehavior(UnLikesBehaviorDTO dto) {
//            1. 校验参数 文章id不能为空  需要登录 不喜欢类型取值为 0 或 1
        // 2. 根据当前登录用户id查询行为实体对象
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
//            3. 如果是 不喜欢操作 查询不喜欢行为是否存在
        Integer id = user.getId();
        ApBehaviorEntry equipmentId = findByUserIdOrEquipmentId(id, dto.getEquipmentId());
        Query query = Query.query(Criteria.where("entryId")
                .is(equipmentId.getId())
                .and("equipmentId")
                .is(dto.getEquipmentId()));
        ApUnlikesBehavior Two = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        Short type = dto.getType();
//            4. 如果不存在   添加不喜欢行为
        if (Two == null) {
            if (type == 1) {
                ApUnlikesBehavior apUnlikesBehavior = new ApUnlikesBehavior();
                apUnlikesBehavior.setEntryId(equipmentId.getId());
                apUnlikesBehavior.setArticleId(dto.getArticleId());
                apUnlikesBehavior.setCreatedTime(new Date());
            } else {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
//            5. 如果是 取消不喜欢操作  删除对应的不喜欢数据
        } else {
            if (Two == null) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            } else {
                mongoTemplate.remove(query, ApUnlikesBehavior.class);
            }
        }
        return ResponseResult
                .okResult();
    }

    @Override
    public ResponseResult collectBehavior(CollectionBehaviorDTO dto) {
        //1.校验参数 需要登录 文章id不能null  操作类型 0 或 1
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.根据userId查询行为实体数据
        ApBehaviorEntry behaviorEntry = findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (behaviorEntry == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"查询行为实体对象为空");
        }
        //3.如果是收藏操作 判断是否已经收藏
        if (dto.getOperation() == 0){
            ApCollection collection = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(behaviorEntry.getId())
                    .and("articleId").is(dto.getArticleId())), ApCollection.class);
            if (collection != null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"已经收藏过");
            }
            //4.如果未收藏 新增收藏行为
            collection = new ApCollection();
            collection.setEntryId(behaviorEntry.getId());
            collection.setArticleId(dto.getArticleId());
            collection.setCreatedTime(new Date());
            mongoTemplate.insert(collection);
        } else {
            //5.如果是取消收藏操作  删除收藏行为
            mongoTemplate.remove(Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("articleId").is(dto.getArticleId())), ApCollection.class);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDTO dto) {
        return null;
    }


}